
#include "Channel.h"

#include <unistd.h>

#include <utility>

#include "EventLoop.h"
#include "Socket.h"

const short Channel::READ_EVENT = 1;
const short Channel::WRITE_EVENT = 2;
const short Channel::ET = 4;

Channel::Channel(int fd, EventLoop *loop) : m_fd(fd), m_loop(loop), m_listen_events(0), m_ready_events(0), m_exist(false) {}

Channel::~Channel() { m_loop->DeleteChannel(this); }

void Channel::HandleEvent() const {
  if (m_ready_events & READ_EVENT) {
    m_read_callback();
  }
  if (m_ready_events & WRITE_EVENT) {
    m_write_callback();
  }
}

void Channel::EnableRead() {
  m_listen_events |= READ_EVENT;
  m_loop->UpdateChannel(this);
}

void Channel::EnableWrite() {
  m_listen_events |= WRITE_EVENT;
  m_loop->UpdateChannel(this);
}

void Channel::EnableET() {
  m_listen_events |= ET;
  m_loop->UpdateChannel(this);
}
int Channel::fd() const { return m_fd; }

short Channel::listen_events() const { return m_listen_events; }
short Channel::ready_events() const { return m_ready_events; }

bool Channel::exist() const { return m_exist; }

void Channel::set_exist(bool in) { m_exist = in; }

void Channel::set_ready_event(short ev) {
  if (ev & READ_EVENT) {
    m_ready_events |= READ_EVENT;
  }
  if (ev & WRITE_EVENT) {
    m_ready_events |= WRITE_EVENT;
  }
  if (ev & ET) {
    m_ready_events |= ET;
  }
}

void Channel::set_read_callback(std::function<void()> const &callback) { m_read_callback = callback; }
void Channel::set_write_callback(std::function<void()> const &callback) { m_write_callback = callback; }
